package com.wxy.demo.client;

import org.apache.cxf.common.util.CollectionUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wangxiaoyuan
 * 2021/3/19 16:28
 **/
public class HttpForClient {
    public static void main(String[] args) throws Exception {
        String requestUrl = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx";
        String namespace = "http://WebXml.com.cn/";
        String method = "getDatabaseInfo";
        Map<String, Object> parameters = new HashMap<>();
//        parameters.put("mobileCode","");
//        parameters.put("userID","");
        String resultTag = "getDatabaseInfoResult";
        //soap服务地址
        StringBuilder soapBuilder = new StringBuilder(64);
        soapBuilder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        soapBuilder.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"").append(namespace).append("\">");
        soapBuilder.append("<soapenv:Header/>");
        soapBuilder.append("<soapenv:Body>");
        soapBuilder.append("<web:").append(method).append(">");
        parameters.forEach((k, v) -> soapBuilder.append("<").append(k).append(">").append(v).append("</").append(k).append(">"));
        soapBuilder.append("</web:").append(method).append(">");
        soapBuilder.append("</soapenv:Body>");
        soapBuilder.append("</soapenv:Envelope>");

        //创建httpcleint对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建http Post请求
        HttpPost httpPost = new HttpPost(requestUrl);
        // 构建请求配置信息
        RequestConfig config = RequestConfig.custom().setConnectTimeout(1000 * 60) // 创建连接的最长时间
                .setConnectionRequestTimeout(1000 * 60) // 从连接池中获取到连接的最长时间
                .setSocketTimeout(1000 * 60) // 数据传输的最长时间10s
                .build();
        httpPost.setConfig(config);
        CloseableHttpResponse response = null;
        try {
            //采用SOAP1.1调用服务端，这种方式能调用服务端为soap1.1和soap1.2的服务
            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");

            //采用SOAP1.2调用服务端，这种方式只能调用服务端为soap1.2的服务
            // httpPost.setHeader("Content-Type", "application/soap+xml;charset=UTF-8");
            StringEntity stringEntity = new StringEntity(soapBuilder.toString(), StandardCharsets.UTF_8.name());
            httpPost.setEntity(stringEntity);
            response = httpClient.execute(httpPost);
            // 判断返回状态是否为200
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                Document soapRes = Jsoup.parse(content);
                Element returnEle = soapRes.getElementsByTag(resultTag).get(0);
                List<String> data = new ArrayList<>();
                if (CollectionUtils.isEmpty(returnEle.children())) {
                    data.add(returnEle.text());
                } else {
                    returnEle.children().forEach(element -> data.add(element.text()));
                }
                System.out.println(data);
            } else {
                System.out.println("调用失败：code=" + statusCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != response) {
                response.close();
            }
            if (null != httpClient) {
                httpClient.close();
            }
        }


    }
}
